<script setup lang="ts">
import { ref } from 'vue'
import { useMessage } from 'naive-ui'
import { loginAPI } from '@/apis'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

import { UserIcon, LockClosedIcon } from '@heroicons/vue/24/solid'

const message = useMessage()
const userStore = useUserStore()
const router = useRouter()

const loginData = ref({
  username: '',
  password: '',
})

const handleLogin = async () => {
  if (!loginData.value.username || !loginData.value.password) {
    message.error('用户名和密码不能为空')
    return
  }

  try {
    const result = await loginAPI(loginData.value)
    userStore.setUserInfo(result)
    message.success('登录成功')
    router.push({ name: 'layout' })
  } catch (error) {
    if (error instanceof Error) {
      message.error('登陆失败：' + error.message)
    } else {
      message.error('登陆失败')
    }
  }
}
</script>

<template>
  <div class="login-container">
    <n-card>
      <template #header>
        <div class="logo-container">
          <img src="@/assets/images/logo.png" />
          <h3>智慧教务系统</h3>
        </div>
      </template>

      <n-form :model="loginData">
        <n-form-item-row label="用户名" path="username">
          <n-input v-model:value="loginData.username" size="large" placeholder="请输入用户名">
            <template #prefix>
              <n-icon :component="UserIcon" />
            </template>
          </n-input>
        </n-form-item-row>

        <n-form-item-row label="密码" path="password">
          <n-input
            v-model:value="loginData.password"
            type="password"
            size="large"
            placeholder="请输入密码"
            show-password-on="click"
          >
            <template #prefix>
              <n-icon :component="LockClosedIcon" />
            </template>
          </n-input>
        </n-form-item-row>

        <n-form-item-row>
          <n-button @click="handleLogin" size="large" type="info" block strong> 登录 </n-button>
        </n-form-item-row>
      </n-form>
    </n-card>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100%;
  padding: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('@/assets/images/login-bg.png') no-repeat;
  background-size: cover;

  .n-card {
    width: 400px;
    border-radius: 8px;

    .logo-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 10px;

      img {
        width: 80px;
        height: 80px;
      }

      h2 {
        text-align: center;
      }
    }
  }
}
</style>
